//
//  HKHealthStore+Extension.m
//  Health
//
//  Created by LeeJay on 16/8/24.
//  Copyright © 2016年 LeeJay. All rights reserved.
//

#import "HKHealthStore+Extension.h"
#import <UIKit/UIKit.h>
#import "StepCountModel.h"
#import "NSDate+Extension.h"

@implementation HKHealthStore (Extension)

- (void)mostRecentQuantitySampleOfType:(HKQuantityType *)quantityType
                             predicate:(NSPredicate *)predicate
                            completion:(void (^)(HKQuantity *, NSError *))completion
{
    NSSortDescriptor *timeSortDescriptor = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierEndDate ascending:NO];
    
    HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:quantityType predicate:nil limit:1 sortDescriptors:@[timeSortDescriptor] resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {
        if (!results) {
            if (completion) {
                completion(nil, error);
            }
            
            return;
        }
        
        if (completion) {
            HKQuantitySample *quantitySample = results.firstObject;
            HKQuantity *quantity = quantitySample.quantity;
            
            completion(quantity, error);
        }
    }];
    
    [self executeQuery:query];
}

- (void)getStepCountStartDate:(NSDate *)startDate
                      endDate:(NSDate *)endDate
                      success:(void (^)(NSArray *))success
                      failure:(void (^)(NSError *))failure
{
    HKQuantityType *quantityType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionStrictEndDate];
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.day = 1;
    
    HKStatisticsCollectionQuery *collectionQuery = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:quantityType quantitySamplePredicate:predicate options:HKStatisticsOptionCumulativeSum | HKStatisticsOptionSeparateBySource anchorDate:startDate intervalComponents:dateComponents];
    
    collectionQuery.initialResultsHandler = ^(HKStatisticsCollectionQuery *query, HKStatisticsCollection * __nullable result, NSError * __nullable error) {
        
        NSMutableArray *returnArr = [NSMutableArray array];
        for (NSInteger i = result.statistics.count - 1; i >= 0; i--) {
            HKStatistics *statistic = result.statistics[i];
            for (HKSource *source in statistic.sources) {
                if ([source.name isEqualToString:[UIDevice currentDevice].name]) {
                    
                    StepCountModel *model = [[StepCountModel alloc] init];
                    model.startDate = [NSDate stringFromDate:statistic.startDate];
                    model.endDate = [NSDate stringFromDate:statistic.endDate];
                    
                    HKQuantity *quantity = [statistic sumQuantityForSource:source];
                    if ([quantity isCompatibleWithUnit:[HKUnit countUnit]]) {
                        model.stepCount = (NSInteger)[quantity doubleValueForUnit:[HKUnit countUnit]];
                    }
                    
                    [returnArr addObject:model];
                }
            }
        }
        
        if (!error) {
            if (success) {
                success(returnArr);
            }
        } else if (failure) {
            failure(error);
        }
    };
    [self executeQuery:collectionQuery];
}

@end
